package com.keta.foundation.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.keta.foundation.dao.UserDAO;
import com.keta.foundation.entity.Module;
import com.keta.foundation.entity.User;
import com.keta.foundation.exception.ExistedException;
import com.keta.foundation.service.UserRoleService;
import com.keta.foundation.service.UserService;
import com.keta.foundation.shiro.ShiroDbRealm;
import com.keta.foundation.shiro.ShiroDbRealm.HashPassword;
import com.keta.foundation.util.dwz.Page;
import com.keta.foundation.util.dwz.PageUtil;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private ShiroDbRealm shiroRealm;

	@Override
	public long getUserCount() {

		return userDAO.count();
	}

	@Override
	public List<User> getAll() {

		return userDAO.findAll();
	}

	@Override
	public List<User> getAll(Page page) {

		org.springframework.data.domain.Page<User> springPage = userDAO.findAll(PageUtil.createPageable(page));
		page.setTotalPage(springPage.getTotalPages());
		page.setTotalCount(springPage.getTotalElements());
		return springPage.getContent();
	}

	public User getByUsername(String userName) {
		return userDAO.getByUsername(userName);
	}

	@Override
	public void saveOrUpdate(User user) {

		User tmpUser = null;
		if (user.getId() == null) {
			// 添加操作
			tmpUser = userDAO.getByUsername(user.getUsername());
			if (tmpUser != null) {
				throw new ExistedException("已经存在" + user.getUsername() + "用户");
			}

			// 处理密码,更新时不处理
			if (StringUtils.isNotBlank(user.getPlainPassword())) {
				HashPassword hashPassword = ShiroDbRealm.encryptPassword(user.getPlainPassword());
				user.setSalt(hashPassword.salt);
				user.setPassword(hashPassword.password);
			}
			user.setCreateTime(new Date());
		} else {
			// 更新操作
			tmpUser = userDAO.findOne(user.getId());
			if (StringUtils.isBlank(user.getPassword()) || StringUtils.isBlank(user.getSalt())) {
				user.setPassword(tmpUser.getPassword());
				user.setSalt(tmpUser.getSalt());
			}
		}

		userDAO.save(user);
		
		// 清除登陆Session
		shiroRealm.clearCachedAuthorizationInfo(user.getUsername());
	}

	@Override
	public User get(Long userId) {
		return userDAO.findOne(userId);
	}

	@Override
	public void delete(Long id) {

		// 删除用户之前删除挂在用户身上的
		userRoleService.delByUser(id);

		userDAO.delete(id);
		// 清除登陆Session
		// shiroRealm.clearCachedAuthorizationInfo(this.get(id).getUsername());
	}

	@Override
	public void restPassword(User user, String newPassword) {
		HashPassword hashPassword = ShiroDbRealm.encryptPassword(newPassword);
		user.setSalt(hashPassword.salt);
		user.setPassword(hashPassword.password);
		this.saveOrUpdate(user);
	}
	
	@Override
	public boolean validPasswrod(User user,String password){
		return ShiroDbRealm.validatePassword(password, user.getPassword(),user.getSalt());
	}

	@Override
	public void updateStatus(User user) {

		if (user.getStatus().equals(User.STATUS_ENABLED)) {
			user.setStatus(User.STATUS_DISABLED);
		} else {
			user.setStatus(User.STATUS_ENABLED);
		}
		shiroRealm.clearCachedAuthorizationInfo(user.getUsername());
		this.saveOrUpdate(user);

		// SecurityUtils.getSecurityManager().
	}

	@Override
	public List<User> getByOrganizationId(Long organizationId) {
		return userDAO.getByOrganizationId(organizationId);
	}

}
